package com.example.demo.service;

import com.example.demo.bean.StudentEntity;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * @program: SpringAOP
 * @ClassName ExcelImportService
 * @description:
 * @author: zsn
 * @create: 2024-10-09 17:20
 * @Version 1.0
 **/
@Service
public class ExcelImportService {
    public List<StudentEntity> importExcel(MultipartFile file) throws IOException {
        List<StudentEntity> users = new ArrayList<>();
        try (InputStream inputStream = file.getInputStream();
             Workbook workbook = new XSSFWorkbook(inputStream)) {

            Sheet sheet = workbook.getSheetAt(0); // 读取第一个工作表
            for (Row row : sheet) {
                if (row.getRowNum() == 0) { // 跳过标题行
                    continue;
                }
                StudentEntity user = new StudentEntity();
                user.setId(String.valueOf(row.getCell(1).getNumericCellValue()));
                user.setName(row.getCell(2).getStringCellValue());
                users.add(user);
            }
        }
        return users;
    }
}